<script lang="ts" setup="">
import { ref } from 'vue'
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue'

const emit = defineEmits(['update:text', 'inputChange'])
let { text, type, check } = defineProps({
    text: {
        type: String,
        default: '',
        required: true
    },
    type: {
        type: String,
        default: 'text',
        required: false
    },
    check: {
        type: Boolean,
        default: false,
        required: false
    }
})

let resetText = ref<string>(text)
let switchToInput = ref<boolean>(false)

function save() {
    emit('update:text', resetText)
    switchToInput.value = false
    if (type != 'text') {
        emit('inputChange', resetText)
    }
}

function edit() {
    switchToInput.value = true
}
</script>

<template>
    <div class="editable-cell">
        <div
            v-if="switchToInput"
            class="editable-cell-input-wrapper"
        >
            <a-input
                v-model:value="resetText"
                @pressEnter="save"
                size="default"
            />
            <check-outlined
                class="editable-cell-icon-check"
                @click="save"
            />
        </div>
        <div
            v-else
            class="editable-cell-text-wrapper"
        >
            <span v-if="type === 'text'">{{ resetText || ' ' }}</span>
            <slot
                v-else
                :text="resetText"
                :check="check"
            ></slot>
            <edit-outlined
                class="editable-cell-icon"
                @click="edit"
            />
        </div>
    </div>
</template>

<style lang="scss" scoped>
.editable-cell {
    width: 100%;
}

.editable-cell-input-wrapper {
    :deep(.ant-input) {
        width: 70%;
    }
}

.editable-cell-icon,
.editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
}

.editable-cell-icon,
.editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
}

.editable-cell-icon {
    margin-top: 4px;
    display: none;
}

.editable-cell-icon-check {
    line-height: 28px;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
    color: #108ee9;
}

.editable-cell:hover .editable-cell-icon {
    display: inline-block;
}
</style>
